<template>
    <div>
      <q-card style="min-height:600px;">
        <q-tabs
        v-model="tab"
        dense
        align="left"
        class="bg-grey-2 text-teal"
        :breakpoint="0"
      >
          <q-tab name="mails" style="padding:5px;font-size:60px !important;" label="品类" ></q-tab>
        </q-tabs>
        <q-tab-panels v-model="tab"  animated>
          <q-tab-panel name="mails">
            <div v-if="nodes.length === 0" style="color:blue">暂无品类, 请联系管理员新增</div>
            <div v-else style="font-size:13px;color:#000000;">
              <q-tree
              style=""
              :nodes="nodes"
              node-key="id"
              label-key="name"
              selected-color="primary"
              :selected.sync="selected"
              ref="trees"
              :expanded.sync="nodeExpand">
              <!-- <template v-slot:header-root="prop">
                <div class="row items-center" style="width:100%">
                  <div class="ellipsis" style="width:82%" :title="prop.node.name">{{ prop.node.name }}</div>
                </div>
                <q-popup-proxy context-menu  v-if="prop.node.active == 1">
                  <q-list dense class="text-grey">
                    <q-item clickable v-close-popup  v-if="prop.node.increase != 0" @click="addChild( prop.node)">
                      <q-item-section>
                        <q-item-label>新增下级品类</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup @click="add(prop.node)">
                      <q-item-section>
                        <q-item-label>新增平级品类</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup @click="editNode( prop.node)">
                      <q-item-section>
                        <q-item-label>修改</q-item-label>
                      </q-item-section>
                    </q-item> -->
                    <!-- <q-item clickable v-close-popup @click="delRow( prop.node)">
                      <q-item-section>
                        <q-item-label>删除</q-item-label>
                      </q-item-section>
                    </q-item> -->
                    <!-- <q-item clickable v-close-popup @click="activees(prop.node, active=0)">
                      <q-item-section>
                        <q-item-label>禁用</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-popup-proxy>
                <q-popup-proxy context-menu  v-if="prop.node.active == 0">
                  <q-list dense class="text-grey">
                    <q-item clickable v-close-popup @click="activees(prop.node, active=1)">
                      <q-item-section>
                        <q-item-label>启用</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item clickable v-close-popup @click="delRow( prop.node)">
                      <q-item-section>
                        <q-item-label>删除</q-item-label>
                      </q-item-section>
                    </q-item> -->
                  <!-- </q-list>
                </q-popup-proxy>
              </template> -->
            </q-tree>
            </div>
          </q-tab-panel>
        </q-tab-panels>
      </q-card>
      <q-dialog
        v-model="addOrEditDialogs"
        persistent
        :maximized="maximizedToggle"
        transition-show="slide-up"
        transition-hide="slide-down">
        <q-card class="bg-white relative-position" style="min-width:40vw">
          <q-bar class="bg-white q-py-lg">
            <strong>{{  addOrEdit === 1? '新增' : '修改' }}</strong>
            <q-space />
            <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
              <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
            </q-btn>
            <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
              <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
            </q-btn>
            <q-btn dense flat icon="close" @click="addOrEditDialogs = false">
              <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
            </q-btn>
          </q-bar>
          <q-separator />
          <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
            <div class="row q-col-gutter-sm">
              <div class="col-12" v-if="nodes.length !== 0 && addOrEditForm.grade !== 0">
                <div>父级</div>
                <div style="border-bottom:1px solid #ccc;margin-top:8px;">{{ addOrEditForm.code }} -- {{ addOrEditForm.name }}</div>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForms.code.$error?'text-negative': ''">编码</div>
                <q-input
                  :disable = 'codeDisable'
                  v-model="addOrEditForms.code"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForms.code.$error"
                  @blur="$v.addOrEditForms.code.$touch"
                  dense hint/>
              </div>
              <div class="col-12" v-if="addOrEdit!==1">
                <div>层级</div>
                <q-input
                  disable
                  v-model="addOrEditForms.grade"
                  dense hint/>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForms.name.$error?'text-negative': ''">名称</div>
                <q-input
                  v-model="addOrEditForms.name"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForms.name.$error"
                  @blur="$v.addOrEditForms.name.$touch"
                  dense hint/>
              </div>
              <div class="col-12">
                <div>英文名称</div>
                <q-input
                  v-model="addOrEditForms.nameEn"
                  dense hint/>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForms.sn.$error?'text-negative': ''">序号</div>
                <q-input
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForms.sn.$error"
                  @blur="$v.addOrEditForms.sn.$touch"
                  v-model="addOrEditForms.sn"
                  dense hint/>
              </div>
              <div class="col-6">
                <div>是否可新增子级</div>
                <q-radio v-model="addOrEditForms.increase" :val=1 color="secondary" label="是" />
                <q-radio v-model="addOrEditForms.increase" :val=0 color="secondary" label="否" />
                <!-- <q-select
                  emit-value
                  map-options
                  dense
                  v-model="addOrEditForms.increase"
                  :options="increaseOption" /> -->
              </div>
              <div class="col-6" v-if=" addOrEdit != 1">
                <div>是否启用</div>
                <q-radio v-model="addOrEditForms.active" :val=1 color="secondary" label="是" />
                <q-radio v-model="addOrEditForms.active" :val=0 color="secondary" label="否" />
                <!-- <q-select
                  emit-value
                  map-options
                  dense
                  v-model="addOrEditForms.active"
                  :options="typeOption" /> -->
              </div>
              <div class="col-12">
                <div>说明</div>
                <q-input
                  maxlength="200"
                  type="textarea"
                  v-model="addOrEditForms.remark"
                  dense hint/>
              </div>
            </div>
          </q-card-section>
          <q-separator class="absolute" style="bottom: 52px; left: 0"/>
          <q-card-actions align="right" class="absolute-bottom bg-white">
            <q-btn flat label="取消" color="primary" v-close-popup />
            <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveHandler" />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog v-model="confirm">
      <q-card  style="min-width: 300px;min-height:200px;position: relative;">
        <q-card-section class="row items-center" style="font-size:20px;margin-top:40px;padding-left:25px;">
          <span class="q-ml-sm">当前节点有子节点,{{actives==1?'启用':'禁用'}}后会影响所有子节点,<br>是否却继续?</span>
        </q-card-section>
        <q-card-actions align="right" style="position: absolute;bottom:0;right:0;">
          <q-btn flat label="否" style="font-size:16px;border:1px solid #029bed;" color="primary" v-close-popup @click="giveup"/>
          <q-btn flat label="是" style="font-size:16px;border:1px solid #029bed;" color="primary"  @click="again"/>
        </q-card-actions>
      </q-card>
    </q-dialog>
    </div>
</template>

<script>

import { required } from 'vuelidate/lib/validators'
import { transformToTreeFormat } from 'src/utils/fns'
export default {
  props: {
    id: {
    },
    name: {}
  },
  name: 'leftNavs',
  data () {
    return {
      codeDisable: false,
      tab: 'mails',
      code: '',
      confirm: false,
      message: 0,
      nodes: [],
      ticked: [],
      selected: 0,
      tickType: 'strict',
      nodeExpand: [],
      nodeSelected: '',
      addOrEdit: 1,
      parentId: '0',
      num: 0,
      maximizedToggle: false,
      loadingSave: false,
      addOrEditDialogs: false,
      addOrEditDialog: false,
      addOrEditForms: {
        id: '',
        name: '',
        grade: '',
        nameEn: '',
        remark: '',
        sn: '0',
        increase: 1,
        active: 1
      },
      actives: '',
      nodeclick: {},
      addOrEditForm: {
        code: '',
        name: '',
        grade: ''
      },
      tree: '',
      typeOption: [
        {
          label: '否',
          value: 0
        },
        {
          label: '是',
          value: 1
        }
      ],
      increaseOption: [
        {
          label: '否',
          value: 0
        },
        {
          label: '是',
          value: 1
        }
      ]
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      increase: { required },
      sn: { required }
    },
    addOrEditForms: {
      name: { required },
      code: { required },
      sn: { required }
      // type: { required }
    }
  },
  created () {
    this.getTree()
    this.getCode()
  },
  watch: {
    'id' () {
      this.getTree()
    },
    'name' () {
      this.getTree()
    },
    'selected' () {
      let select = this.selected
      let d = []
      function getarr (arr) {
        for (let i in arr) {
          if (arr[i].id === select) {
            d.push(arr[i])
            break
          } else {
            if (arr[i].children instanceof Array) {
              getarr(arr[i].children)
            }
          }
        }
      }
      getarr(this.nodes)
      console.log(d)
      this.$emit('treeId', d)
    }
  },
  methods: {
    async getCode () {
      let data = {
        typeCode: 700012
      }
      await this.$api({
        method: 'post',
        url: '/common/serial/generate',
        params: data,
        emulateJSON: true,
        useNotify: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          if (data === null) {
            this.codeDisable = false
          } else {
            this.codeDisable = true
            this.code = data
          }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async addcategory () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        if (this.addOrEdit === 1) {
          await this.$api({
            method: 'put',
            url: '/mdm/category/add',
            params: {
              categoryTypeId: this.message,
              sn: this.addOrEditForm.sn,
              name: this.addOrEditForm.name,
              nameEn: this.addOrEditForm.nameEn,
              increase: this.addOrEditForm.increase,
              parentId: this.parentId,
              remark: this.addOrEditForm.remark
            },
            emulateJSON: true,
            useNotify: true,
            useLoadLayer: true,
            successCallback: ({ data }) => {
              console.log(data)
              this.data = data
              this.addOrEditDialog = false
              console.log('4566333')
              this.parentId = 0
              this.addOrEdit = 1
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
          console.log('111111111111111')
        }
        if (this.addOrEdit === 2) {
          await this.$api({
            method: 'put',
            url: '/mdm/category/update',
            params: {
              categoryTypeId: this.message,
              sn: this.addOrEditForm.sn,
              name: this.addOrEditForm.name,
              nameEn: this.addOrEditForm.nameEn,
              increase: this.addOrEditForm.increase,
              id: this.parentId,
              remark: this.addOrEditForm.remark
            },
            emulateJSON: true,
            useNotify: true,
            useLoadLayer: true,
            successCallback: ({ data }) => {
              this.data = data
              this.addOrEditDialog = false
              this.parentId = 0
              this.addOrEdit = 1
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
        }
        if (this.addOrEdit === 3) {
          await this.$api({
            method: 'put',
            url: '/mdm/category/add',
            params: {
              categoryTypeId: this.message,
              sn: this.addOrEditForm.sn,
              name: this.addOrEditForm.name,
              nameEn: this.addOrEditForm.nameEn,
              increase: this.addOrEditForm.increase,
              parentId: this.parentId,
              remark: this.addOrEditForm.remark
            },
            emulateJSON: true,
            useNotify: true,
            useLoadLayer: true,
            successCallback: ({ data }) => {
              this.data = data
              this.addOrEditDialog = false
              this.parentId = 0
              this.addOrEdit = 1
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
        }
        this.getTree()
      }
    },
    delect (text) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除品类：${text.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/category/delete/${text.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
            this.getTree()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }).onCancel(() => { })
    },
    editNode (text) {
      // console.log(text)
      this.addOrEdit = 2
      this.message = text.categoryTypeId
      console.log(text.name)
      this.add(text)
    },
    addChild (text) {
      this.$v.addOrEditForms.$reset()
      this.addOrEdit = 1
      this.addOrEditForm.code = text.code
      this.addOrEditForm.name = text.name
      this.addOrEditForm.grade = 1
      this.addOrEditForms = {
        id: '',
        code: this.code,
        grade: '',
        name: '',
        nameEn: '',
        remark: '',
        active: 1,
        sn: '0',
        increase: 1
      }
      this.parentId = text.id
      this.addOrEditDialogs = true
    },
    async getTree () {
      if (this.id !== '' && this.name !== '') {
        await this.$api({
          method: 'post',
          url: `/mdm/category/query`,
          params: {
            categoryTypeId: this.id
          },
          emulateJSON: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            this.nodes = []
            console.log(this.nodes)
            console.log(data)
            let datas = data
            datas.map(item => {
              item.header = 'root'
              this.nodeExpand.push(item.id)
              item.name = String(item.code) + '-' + String(item.name)
            })
            let nodesCat = transformToTreeFormat(datas, 'id', 'parentId', 'children')
            this.nodes = nodesCat
            console.log(this.selected)
            if (this.selected === 0) {
              console.log('1111111111111111')
              this.selected = this.nodes[0].id
            }
            this.num = this.num + 1
            this.$emit('change', this.num)
            console.log(this.nodes)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }
    },
    // async getTree () {
    //   await this.$api({
    //     method: 'post',
    //     url: `/mdm/categoryType/selectTypeAndCategoriesByTenantId`,
    //     emulateJSON: true,
    //     useLoadLayer: true,
    //     successCallback: ({ data }) => {
    //       let datas = data
    //       for (let i in datas) {
    //         datas[i].header = 'inner'
    //         datas[i].footer = 'none'
    //         if (datas[i].children instanceof Array) {
    //           datas[i].children.map(item => {
    //             item.header = 'root'
    //             datas[i].children = transformToTreeFormat(datas[i].children, 'id', 'parentId', 'children')
    //           })
    //         }
    //       }
    //       console.log(datas)
    //       this.nodes = datas
    //       this.selected = this.nodes[0].id
    //       console.log(this.nodes)
    //     },
    //     errorCallback (err) {
    //       console.log('未处理的业务级error：', err)
    //     }
    //   })
    // },
    // 新增
    add (text) {
      this.$v.addOrEditForms.$reset()
      this.addOrEditForm.grade = 0
      if (this.addOrEdit === 1) {
        this.addOrEditForms = {
          id: '',
          code: this.code,
          name: '',
          nameEn: '',
          grade: '',
          remark: '',
          active: 1,
          sn: '0',
          increase: 1
        }
        this.parentId = 0
      } else if (this.addOrEdit === 2) {
        let index = text.name.lastIndexOf('-')
        let str = text.name
        this.addOrEditForms = {
          id: text.id,
          code: text.code,
          name: str.slice(index + 1, str.length),
          grade: text.grade,
          nameEn: text.nameEn,
          remark: text.remark,
          active: text.active,
          sn: text.sn,
          increase: text.increase
        }
        this.parentId = text.parentId
        if (text.grade === 0) {
          console.log(text)
          this.addOrEditForm.grade = 0
        } else {
          console.log(text)
        }
      }
      this.addOrEditDialogs = true
    },
    activees (prop, active) {
      this.nodeclick = prop
      console.log('963')
      if (active === 1 && prop.isLeaf === 0) {
        console.log('1111111111111111111111111111')
        this.actives = 1
        this.confirm = true
      } else if (active === 0 && prop.isLeaf === 0) {
        this.actives = 2
        this.confirm = true
      } else {
        this.again()
      }
      this.selected = this.nodeclick.id
    },
    giveup () {
      this.confirm = false
      this.getTree()
    },
    async again () {
      let active
      if (this.active === 1) {
        active = 1
      } else {
        active = 0
      }
      await this.$api({
        method: 'delete',
        url: `/mdm/category/active/${this.nodeclick.id}/${active}`,
        params: {
          id: this.nodeclick.id,
          active: this.actives === 1 ? 1 : 0
        },
        emulateJSON: true,
        useNotify: true,
        successCallback: ({ data }) => {
          this.loadingSave = false
          this.confirm = false
          this.getTree()
          this.getCode()
          this.num = this.num + 1
          this.$emit('change', this.num)
          this.addOrEdit = 1
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async saveHandler () {
      this.addOrEditForms.active = Number(this.addOrEditForms.active)
      this.$v.addOrEditForms.$touch()
      if (!this.$v.addOrEditForms.$error) {
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: this.addOrEdit === 1 ? '/mdm/category/add' : '/mdm/category/update',
          params: {
            id: this.addOrEditForms.id,
            code: this.addOrEditForms.code,
            categoryTypeId: this.id,
            sn: this.addOrEditForms.sn,
            name: this.addOrEditForms.name,
            nameEn: this.addOrEditForms.nameEn,
            increase: this.addOrEditForms.increase,
            parentId: this.parentId,
            active: this.addOrEditForms.active,
            remark: this.addOrEditForms.remark
          },
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditDialogs = false
            this.loadingSave = false
            this.getTree()
            this.getCode()
            this.num = this.num + 1
            this.$emit('change', this.num)
            this.addOrEdit = 1
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
      }
    },
    // 删除
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/categoryType/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.getTree()
      }).onCancel(() => {

      })
    }
  }
}
</script>

<style lang="stylus" scoped>
/deep/.q-tab__label
  font-size 16px

</style>
